/*
 * Copyright 2016 Yan Zhenjie
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mingmen.canting.caigourenyuan;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mingmen.canting.R;
import com.mingmen.canting.activity.MultipleChoiceActivity;
import com.mingmen.canting.adapter.SelectGongYingAdapter;
import com.mingmen.canting.base.BaseBean;
import com.mingmen.canting.definerecycleview.SwipeRecyclerView;
import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.httpconfig.HttpResponse;
import com.mingmen.canting.immersionbar.ImmersionBar;
import com.mingmen.canting.label.adapter.MultipleRecyclerAdapter;
import com.mingmen.canting.label.bean.LabelTestBean;
import com.mingmen.canting.label.recycler.OnItemClickListener;
import com.mingmen.canting.model.GongYingShangModel;
import com.mingmen.canting.model.PeiSongDetailModel;
import com.mingmen.canting.model.SelectGongModel;
import com.mingmen.canting.util.GsonUtil;
import com.mingmen.canting.util.MyStringUtils;
import com.mingmen.canting.util.SharePreferenceUtil;
import com.mingmen.canting.util.ToolList;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;


/**
 * <p>
 * ListView形式的侧滑菜单，支持横向和竖向的。
 * </p>
 * Created by Yan Zhenjie on 2016/7/27.
 */
public class ChongXinGongYingActivity extends Activity {

    @BindView(R.id.text_return)
    TextView textReturn;
    @BindView(R.id.linear_return)
    LinearLayout linearReturn;
    @BindView(R.id.text_center)
    TextView textCenter;
    @BindView(R.id.img_right)
    ImageView imgRight;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.mToolbar)
    Toolbar mToolbar;


    @BindView(R.id.rv_gongyingshang)
    SwipeRecyclerView rv_gongyingshang;

    String token;
    String billId;
    SelectGongYingAdapter selectGongYingAdapter;

    List<SelectGongModel.DataBean> dataBeanList = new ArrayList<>();

    List<String> getBillDetailIds = new ArrayList<>();
    @BindView(R.id.btn_yes)
    Button btn_yes;
    String supplierId;
    @BindView(R.id.text_billId)
    TextView text_billId;
    @BindView(R.id.check_All)
    CheckBox check_All;
    String cancelReason;

    String pictureList;
    Context mContext;
    int myflag = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chongxin);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        textCenter.setText("选择供应商");
        ImmersionBar.with(this).titleBar(mToolbar)
                .navigationBarColor(R.color.black).init();
        mContext = this;
        token = (String) SharePreferenceUtil.get(this, "token", "");
        billId = getIntent().getStringExtra("billId");
        cancelReason = getIntent().getStringExtra("cancelReason");
        pictureList = getIntent().getStringExtra("pictureList");
        text_billId.setText(billId);
        rv_gongyingshang.setLayoutManager(new LinearLayoutManager(this));
        selectGongYingAdapter = new SelectGongYingAdapter(this, dataBeanList);
        rv_gongyingshang.setAdapter(selectGongYingAdapter);
        getData();
        check_All.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {

                    Log.d("dataBeanList",dataBeanList.size()+"");

                    myflag = 0;
                    for (int i = 0; i < dataBeanList.size(); i++) {
                        dataBeanList.get(i).setSelect(true);
                        JSONObject jsonObject = new JSONObject();
                        supplierId = dataBeanList.get(0).getSupplierId();
                        try {
                            jsonObject.put("billDetailId", dataBeanList.get(i).getBillDetailId());
                            jsonObject.put("amount", dataBeanList.get(i).getAmount() + "");
                            jsonObject.put("price", dataBeanList.get(i).getConfirmPrice() + "");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        getBillDetailIds.add(dataBeanList.get(i).getBillDetailId());

                    }

                    selectGongYingAdapter.notifyDataSetChanged();
                    ToolList.removeDuplicateWithOrder(getBillDetailIds);
                } else {

                    if (myflag == 0) {
                        for (int i = 0; i < dataBeanList.size(); i++) {
                            dataBeanList.get(i).setSelect(false);
                        }
                        getBillDetailIds.clear();
                        selectGongYingAdapter.notifyDataSetChanged();

                    } else {


                    }
                }
            }
        });


    }

    public void getData() {
        HttpResponse.listOrderDetail(token, billId, new StringCallback(this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                SelectGongModel selectGongModel = new SelectGongModel();
                selectGongModel = GsonUtil.GsonToBean(s, SelectGongModel.class);
                dataBeanList.addAll(selectGongModel.getData());
                selectGongYingAdapter.setDataList(dataBeanList);
            }
        });

        selectGongYingAdapter.setOnItemClickListener(new SelectGongYingAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(View view, int pos, List<SelectGongModel.DataBean> myLiveList) {
                for (SelectGongModel.DataBean cart : dataBeanList) {
                    if (cart.isSelect()) {   //是否勾上去了
                        Log.d("勾选上了", "勾选上了");
                        supplierId = myLiveList.get(pos).getSupplierId();
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("billDetailId", cart.getBillDetailId());
                            jsonObject.put("amount", cart.getAmount() + "");
                            jsonObject.put("price", cart.getConfirmPrice() + "");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
//                                applyList.add(jsonObject.toString());
//                                ToolList.removeDuplicateWithOrder(applyList);
                        Log.d("JSONOBJECTOBJECT", jsonObject.toString());
                        myflag = 0;
                        getBillDetailIds.add(cart.getBillDetailId());
                        ToolList.removeDuplicateWithOrder(getBillDetailIds);

                        if (getBillDetailIds.size()==myLiveList.size()){
                            check_All.setChecked(true);
                        }

                    } else {
                        Log.d("取消勾选", "取消勾选");

                        if (getBillDetailIds.size() > 0) {
                            for (int i = 0; i < getBillDetailIds.size(); i++) {
                                if (getBillDetailIds.get(i).contains(cart.getBillDetailId())) {
                                    getBillDetailIds.remove(i);
                                }
                            }
                        }

                        myflag = 1;
                        check_All.setChecked(false);
                        ToolList.removeDuplicateWithOrder(getBillDetailIds);
                    }
                }
            }
        });

    }


    @OnClick({R.id.text_return, R.id.linear_return, R.id.text_center, R.id.btn_yes})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.text_return:
                finish();
                break;
            case R.id.linear_return:
                finish();
                break;


            case R.id.text_center:
//                startActivity(new Intent(ChongXinGongYingActivity.this, MultipleChoiceActivity.class));
                break;
            case R.id.btn_yes:
                String sendbilldetail = MyStringUtils.returnStringBuffer(getBillDetailIds);
                if (getBillDetailIds.size()==0){
                    Toast.makeText(mContext, "请选择商品", Toast.LENGTH_SHORT).show();
                }else {
                    HttpResponse.changeSupplierNewOrder(token, cancelReason, pictureList, supplierId, sendbilldetail, new StringCallback(this) {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            BaseBean baseBean = new BaseBean();
                            baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                            if (baseBean.getCode() == 0) {
                                EventBus.getDefault().post(4);
                                EventBus.getDefault().post(3);
                                EventBus.getDefault().post(2);
                                finish();
                            }
                            Toast.makeText(ChongXinGongYingActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                break;
        }
    }

    public void onEventMainThread(Integer a) {

    }
}